﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Beginning.Api.Application.Command.ScionChange;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigDeath
{
    public class DelPigDeathHandler : IRequestHandler<DelPigDeathCommand, Result>
    {
        /// <summary>
        /// 猪只死亡仓储
        /// </summary>
        private readonly IBaseRepository<PigDeaths> pigDeathsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="pigDeathsRepository"></param>
        public DelPigDeathHandler( IBaseRepository<PigDeaths> pigDeathsRepository)
        {
            this.pigDeathsRepository = pigDeathsRepository;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DelPigDeathCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var list = await(await pigDeathsRepository.GetAll()).Where(d => d.PigDeathId == request.PigDeathId).FirstAsync();
                if (list != null)
                {
                    list.IsPigDeath= 1;
                }
                var res = await pigDeathsRepository.Update(list);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "猪只死亡删除成功";
                }
            }
            catch (Exception)
            {
                result.Msg = "猪只死亡删除异常";
            }
            return result;
        }
    }
}
